//
//  YCNewViewController.m
//  LOLBox
//
//  Created by mac on 15-3-27.
//  Copyright (c) 2015年 Honey. All rights reserved.
//

#import "YCNewViewController.h"
#import "HttpRequestManager.h"
#import "YCNewSModel.h"
#import "YCNewTableViewCell.h"
#import "YCDetailsViewController.h"
#import "HXADBanner.h"
#import "MJRefresh.h"
#import "YCAppDelegate.h"
#import "AFNetworking.h"
#import "PublicNavView.h"
#import "YCSearchViewController.h"
#import "PublicUINav.h"
//w网址
#import "NetInterface.h"


@interface YCNewViewController ()<MJRefreshBaseViewDelegate,UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
{
    HXADBanner *_banner;
    NSInteger _page;
    BOOL _isFirst;
    
    // 刷新
    MJRefreshFooterView *_footerView;
    MJRefreshHeaderView *_headerView;
    MJRefreshBaseView *_baseView;
    
}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation YCNewViewController

- (void)viewWillAppear:(BOOL)animated
{
    YCAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate showTabBar];
    animated = YES;
    
}


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [self createNavTitleView:@"新闻资讯"];
        [self search];
    }
    return self;
}
//搜索功能
- (void)search
{
    UIBarButtonItem *barbtn = [[UIBarButtons alloc] createSearchBarButtonWithTarget:self WithAction:@selector(searchSome:)];
    UIBarButtonItem *space = [[UIBarButtons alloc] createSpaceButtonWithWidth:-10];

    self.navigationItem.rightBarButtonItems = @[space,barbtn];
}
- (void)searchSome:(UIBarButtons *)btn
{
    self.navigationItem.titleView.hidden = YES;
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 220, 30)];
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:v.frame];
    imgView.image = [UIImage imageNamed:@"search_textfield"];
    
    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(30, 0, 220, 30)];
    tf.placeholder = @"输入关键字搜索";
    tf.font = [UIFont systemFontOfSize:14];
    tf.delegate = self;
    tf.clearButtonMode = UITextFieldViewModeAlways;
    tf.returnKeyType = UIReturnKeySearch;
    [tf becomeFirstResponder];
    //tf.background = [UIImage imageNamed:@"search_textfield"];
    
    [v addSubview:imgView];
    [v addSubview:tf];
    UIBarButtonItem *seaTextFeid = [[UIBarButtonItem alloc] initWithCustomView:v];
    
    UIBarButtonItem *barbtn = [[UIBarButtons alloc] createCancelBarButtonWithTarget:self WithAction:@selector(cancelSearch)];
    UIBarButtonItem *space = [[UIBarButtons alloc] createSpaceButtonWithWidth:-10];
    
    self.navigationItem.leftBarButtonItem = seaTextFeid;
    self.navigationItem.rightBarButtonItems = @[space,barbtn];
    
}

- (void)cancelSearch
{
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.titleView.hidden = NO;
    [self search];
}

#pragma mark - UITextFieldDelegate
//搜索进去搜索页面
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //隐藏键盘
    [textField resignFirstResponder];
    //取消文本框
    [self cancelSearch];
    
    NSString *s = [textField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //NSString *bb = [s stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSString *str = [NSString stringWithFormat:kSearchUrl,s];
    
    YCSearchViewController *sea = [[YCSearchViewController alloc] init];
    [sea senderUrl:str withWhat:textField.text];
    [self.navigationController pushViewController:sea animated:YES];
    
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    return YES;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _page = 1;
    _isFirst = YES;

   // NSLog(@"22222");
    //[self createimg];
    [self createBanner];
    /**
     *  初始化导航条下面的导航条
     */
    [self createNavView];
    
    [self.dataSource removeAllObjects];
    /**
     数据请求
     */
    [self AFN:kNewestUrl page:_page];

    /**
     实例化TableView
     */
    [self initTableView];
    
    [self initFooterView];
    [self initHeaderView];

}

//滚动视图
- (void)createBanner
{
    _banner = [[HXADBanner alloc] init];
    _banner.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 140);
    
    NSMutableArray *dataArr = [NSMutableArray array];
    NSMutableArray *dataIdArr = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:kBanner parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //NSLog(@"---%@",arr);
        [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString *img = obj[@"img"];
            if (img.length != 0)
            {
                [dataArr addObject:img];
            }
            //存入ID
            [dataIdArr addObject:obj[@"id"]];
        }];
        
        _banner.arrays = dataArr;
        [_banner setArrays:dataArr];
        _banner.IDArray = dataIdArr;
        //[self.view addSubview:_banner];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"错误");
    }];
    
    __weak PublicUINav *nav = (PublicUINav *)self.navigationController;
    _banner.banBlock = ^(NSInteger index){
        
        YCDetailsViewController *details = [[YCDetailsViewController alloc] init];
        //NSLog(@"sss:%@",model.Id);
        [details senderBannerId:dataIdArr[index - 1000]];
        [nav pushViewController:details animated:YES];
    };
}
- (void)createNavView
{
    NSArray *nameArr =  @[@"最新",@"热评",@"官方",@"外服",@"赛事",@"攻略"];
    NSArray *urlArr = @[News0,
                        News1,
                        News2,
                        News3,
                        News4,
                        News5];
    PublicNavView *navView = [[PublicNavView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    //navView.backgroundColor = [UIColor blueColor];
    // 第一步，把数组传过去
    [navView senderValue:nameArr andSecond:urlArr];
    //第二步，创建按钮
    [navView creatTheBtnAndIndex:0];
    //第三步，通过BLOCK回调得到网址
    [navView changValue:@"1" senderBlock:^(NSString *str,NSInteger index) {
        //NSLog(@"str :%@",str);
        if (self.dataSource.count > 0) {
            [self.dataSource removeAllObjects];
        }
        
        BOOL bbk = [str isEqualToString:kNewestUrl];
        if (bbk)
        {
            _isFirst = YES;
            [self createBanner];
            self.tableView.tableHeaderView = _banner;
            //[self.tableView reloadData];
        }
        else
        {
            _isFirst = NO;
            self.tableView.tableHeaderView = nil;
        }
        //NSLog(@"sender:%@",str);
        
        [self AFN:str page:_page];
        
    }];
    
    [self.view addSubview:navView];
}



//数据下载
- (void)AFN:(NSString *)str page:(NSInteger)page
{
    [[HttpRequestManager shareInstance] getNewsInfo:str andPage:page withSuccess:^(HttpRequestManager *manager, NSMutableArray *arr) {
        //NSLog(@"1");
        self.dataSource = arr;
        [self.tableView reloadData];
        
        [_baseView endRefreshing];

    } andFailure:^(HttpRequestManager *manager, NSError *error) {
        NSLog(@"-1");
        
        [_baseView endRefreshing];
    }];
}


- (void)initTableView
{
    //CGRect rect = [UIScreen mainScreen].bounds;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height - 64 - 50 - 30) style:UITableViewStylePlain];
    
    //self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 95;
    //self.tableView.sectionHeaderHeight = 300;
    if (_isFirst)
    {
        self.tableView.tableHeaderView = _banner;
    }
//    self.tableView.backgroundColor = [UIColor redColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    /**
     *  去掉多余的线
     */
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = v;
    
    // 注册Cell
    [self.tableView registerClass:[YCNewTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.view addSubview:self.tableView];
    
}
#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YCNewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (self.dataSource.count > 0)
    {
        YCNewSModel *model = self.dataSource[indexPath.row];
        [cell fillCellWithModel:model];
    }
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YCNewSModel *model = self.dataSource[indexPath.row];
    YCDetailsViewController *details = [[YCDetailsViewController alloc] init];
    //NSLog(@"sss:%@",model.Id);
    //self.navigationController.hidesBottomBarWhenPushed = YES;
    [details senderNewsModel:model];
    [self.navigationController pushViewController:details animated:YES];
    //self.tabBarController.tabBar.hidden = YES;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createimg
{
    UIImageView *v = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame), 320, 50)];
    v.backgroundColor = [UIColor blackColor];
    [self.view addSubview:v];
}


- (void)dealloc
{
    [_headerView free];
    [_footerView free];
}

- (void)initHeaderView
{
    _headerView = [[MJRefreshHeaderView alloc] initWithScrollView:_tableView];
    _headerView.delegate = self;
}

- (void)initFooterView
{
    _footerView = [[MJRefreshFooterView alloc] initWithScrollView:_tableView];
    _footerView.delegate = self;
}

#pragma mark - MJRefreshBaseViewDelegate

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    _baseView = refreshView;
    
    if (_baseView == _headerView)
    {
        NSLog(@"刷新");
        
        if (_dataSource.count > 0)
        {
            [_dataSource removeAllObjects];
        }
        _page = 1;
    }
    else
    {
        NSLog(@"加载更多");
        _page++;
    }
    
    NSLog(@"see%d",_page);
    [self AFN:kNewestUrl page:_page];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
